<?php
/**
 * ClassName: cases
 * Description: 患者病历控制器
 * @Author 周昌
 * @Create 2023/12/7 11:38
 */

namespace app;


use epii\server\Args;
use libs\Tool;
use model\ArchivesModel;
use model\CasesModel;
use model\MedicineModel;
use model\PrescriptModel;
use model\RecuperateModel;
use model\WaitModel;
use service\admin\ArchivesService;
use service\admin\CardService;
use service\admin\HospitalService;
use service\admin\CasesService;
use service\admin\MemberService;
use service\admin\PrescriptService;
use service\admin\RoleService;
use service\admin\TreatmentCateService;
use service\admin\TreatmentServicesService;
use service\admin\WaitService;

class cases extends base
{
    protected $admin_allow=['index','ajax_data','person_times'];
    public function init()
    {
        parent::init();
        $this->accessDenied();
        //静态文件路径
        $this->assign('cases',Tool::getDomain().'/static/cases/');

    }
    public function index()
    {   $archives_id=Args::params('archives_id/d');
        if($this->adminInfo['role']==1){
            $this->assign('hospitals',HospitalService::getSelect());
        }
        $this->_as_archives_id=$archives_id;
        $this->adminUiDisplay();
    }
    //待支付列表
    public function pay_index()
    {
        $payment_status=Args::params('payment_status/d');
        $archives_id=Args::params('archives_id/d');
        if($this->adminInfo['role']==1){
            $this->assign('hospitals',HospitalService::getSelect());
        }
        $this->_as_payment_status=$payment_status;
        $this->_as_archives_id=$archives_id;
        $this->adminUiDisplay();
    }

    public function ajax_data()
    {
        $map = [];
//        //登录用户权限判断
//        $hospital_id=$this->adminInfo['hospital_id'];
//        if($hospital_id){
//            $map[]=['hospital_id','=',$hospital_id];
//        }
        $archives_id=Args::params('archives_id');
        if($archives_id){
            $map[]=['c.archives_id','=',$archives_id];
        }
        $payment_status=Args::params('payment_status/d');
        if(is_int($payment_status)&&$payment_status>=0){
            $map[]=['c.payment_status','=',$payment_status];
        }
        $name = Args::params('name');
        if ($name) {
            $map[] = ['c.name', "LIKE", '%' . $name . '%'];
        }

        $hospital_id = Args::params('hospital_id');
        if ($hospital_id) {
            $map[] = ['c.hospital_id', "=", $hospital_id];
        }
        echo CasesService::getAjaxData($map);
    }
    //问诊
    public function add_edit()
    {
        $wait_id = Args::params('wait_id/d');
        $wait_info=WaitModel::getInfo(['id'=>$wait_id],'admin_id,archives_id,case_id,type,status');
        $id=$wait_info['case_id']?:0;
       // 第一次打开问诊先保存case
        if(!$id){
            $insert=[
                'hospital_id'=>$this->adminInfo['hospital_id'],
                'look_over'=>[],
                'smell'=>[],
                'ask'=>'',
                'pulse_taking'=>[],
                'body'=>'',
            ];
            $insert['archives_id']=$wait_info['archives_id'];
            $insert['admin_id']=$this->adminInfo['id'];
            $case_res=CasesService::addEdit($insert,$wait_id);
            $id=$case_res['data']['case_id'];
        }
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = Args::params('r');
            if($wait_info['status']>WaitService::$wait_status_index['progress']){
                $this->error('该问诊已结束或已取消无法保存');
            }
            //登录权限判断
            $hospital_id=$this->adminInfo['hospital_id'];
            if(!empty($hospital_id)){
                $data['hospital_id']=$hospital_id;
            }
            //验证
            $data['archives_id']=$wait_info['archives_id'];
            $this->validate($data,[
                'hospital_id|所属医院'=>'require|integer|>:0',
//                'admin_id|问诊医生'=>'require|integer|>:0',
                'archives_id|患者id'=>'require|integer|>:0',
//                'age|年龄'=>'require|integer|>:0',
                'main_desc|主述'=>'max:500',
                'look_over|望'=>'',
                'smell|闻'=>'',
                'ask|问'=>'',
                'pulse_taking|切'=>'',
                'body|人体图'=>'',
                'allergy_history|过敏史'=>'max:500',
                'analysis|综合分析'=>'max:500',
            ]);
            $res=CasesService::addEdit($data,$wait_id,$id?:null);
            $res['code']?$this->success($res['msg'],'refresh'):$this->error($res['msg']);
        }
        //case 诊疗记录信息
        $case_info=CasesService::getCaseInfo($id);
        $this->_as_info =  $case_info;
        //患者基础信息
        $member_info=ArchivesModel::getInfo(['id'=>$wait_info['archives_id']]);
        $member_info['sex']=MemberService::$sex[$member_info['sex']];
        $member_info['age']=$case_info['age']?:'';
        $this->assign('member_info',$member_info);

        //治疗服务分类列表
        $treatment_cate=TreatmentCateService::getSelect(['hospital_id'=>$this->adminInfo['hospital_id'],'status'=>1],'id,name',['sort'=>'desc','id'=>'asc']);
        //问诊 治疗服务已选治疗项
        $treatment_services=TreatmentServicesService::getTreatmentServices($id);
        $this->assign('treatment_cate',$treatment_cate);
        $this->assign('treatment_services',$treatment_services);
        //开药处方信息
        $prescript_id= PrescriptModel::getValue(['case_id'=>$id],'id');
        $prescript=PrescriptService::prescriptInfo($prescript_id);
        $prescript['addtime']=$prescript['addtime']??date('Y-m-d H:i:s',time());
        $prescript['admin_name']=$prescript['admin_name']??$this->adminInfo['group_name'];
        $this->_as_prescript=  $prescript;
        //药品列表
        $medicine_list=MedicineModel::getList(['hospital_id'=>$this->adminInfo['hospital_id'],'status'=>1],"id,CONCAT(abbr_name, '-',name) as name,price,unit,common_does as quantity");
        $this->assign('medicine_list',json_encode($medicine_list));
        //调理记录
        $recuperate=RecuperateModel::getInfo(['case_id'=>$id],'content,addtime');
        $this->assign('recuperate',$recuperate);
        $this->assign('wait_id',$wait_id);
        $this->assign('wait_info',$wait_info);
        $this->assign('case_id',$id);
        $this->_as_education=ArchivesService::archivesEducationSelect();
        $this->adminUiDisplay();
    }
    // 病历下 诊疗信息
    public function info()
    {
        $id = Args::params('id/d');
        //case 诊疗记录信息
        $case_info=CasesService::getCaseInfo($id);
        $this->_as_info =  $case_info;
        $this->adminUiDisplay();
    }
    //修改状态
    public function status(){
        $id=Args::params('id/d/1','id,不能为空');
        $status=Args::params('status');
        $res=CasesService::status($id,$status);
        if($res['code']){
            $this->success('成功','refresh');
        }
        $this->error();
    }

    /**
     * @return array|false|string* 删除
     */
    public function del()
    {
        $id = Args::params('id');
        //todo 判断治疗项目下是否已经有订单，无则可以删除
        $res = CasesService::del($id);
        if ($res['code']) {
            $this->success($res['msg'],'refresh');
        } else {
            $this->error($res['msg']);
        }
    }
    // 问诊下  年龄编辑
    public function ageEdit()
    {
        $id=Args::params('id/d');
        $field=Args::params('field');//编辑的字段名
        $field_value=Args::params('field_value');//修改后的值
        $res=CasesService::edit($id,[$field=>$field_value]);
        $res['code']?$this->jsonSuccess($res['msg']):$this->jsonError($res['msg']);
    }
    //支付 线下/卡
    public function pay()
    {
        $id = Args::params('id');
        $money = Args::params('money');
        if (Args::isPost()){

            $data=Args::params('r');
            $data['money']=(float)$money;
            //验证
            $message=[
                'money|支付金额'=>'require|float|>=:0',
                'pay_type|支付方式'=>'require|integer|>=:0',
            ];
            //根据支付的不同，增加不同的验证
            if($data['pay_type']=='0'){
                $message['card_id|卡id']='require|integer|>:0';
            }
            if($data['pay_type']=='1'){
                $data['desc']=trim($data['desc']);
                $message['desc|支付简介']='require|max:225';
            }
            if($data['pay_type']=='2'){
                $this->error('功能开发中暂不可用');
            }
            $this->validate($data,$message);
            $res=CasesService::casePay($id,$data);
            $res['code']?$this->success($res['msg']):$this->error($res['msg']);
        }
        $info=CasesModel::getInfo(['id'=>$id]);
        $info['money']=$money;
        $this->_as_info =$info;
        $this->_as_id = $id;
        $this->_as_money = $money;
        $this->_as_payment_status = CasesService::casePaymentSelect();
        $this->_as_pay_type = CasesService::casePayTypeSelect();
        $member_id=ArchivesModel::getValue(['id'=>$info['archives_id']],'member_id');
        $this->_as_card_list=CardService::getCardList($member_id);

        $this->adminUiDisplay();
    }
    //完成治疗服务人次统计
    public function person_times(){
        if (Args::isPost()){
            //筛选
            if($this->adminInfo['hospital_id']){
                $hospital_id=$this->adminInfo['hospital_id'];
            }else{
                $hospital_id=Args::params('hospital_id');
            }
            $year=Args::params('year');
            echo CasesService::personTimes($year?:null,$hospital_id?:null);
            die;
        }
        if($this->adminInfo['role']==RoleService::$role['admin']['id']){
            $this->assign('hospitals',HospitalService::getSelect());
        }
        $this->adminUiDisplay();
    }

}